<script>
import {getWarehouseListByProductAndUserID} from "@/api/warehouse";
import {getUserInfo} from "@/utils/auth";
import {isNotANumberOrEmpty} from "@/utils";

export default {
  props: ["value", "useDisabled", "useDisabledTable"],
  data() {
    return {
      options: [],
      innerValue: '',
      productID: '',
    }
  },
  watch: {
    value() {
      this.innerValue = this.value;
    },
    innerValue() {
      this.$emit('setValue', this.innerValue);
    },
  },
  mounted() {
  },
  methods: {
    useDisabledTableMethod() {
      if (this.useDisabled) {
        let useList = [];
        for (let j = 0; j < this.options.length; j++) {
          let option = this.options[j];
          option.disabled = false;
        }

        for (let i = 0; i < this.useDisabledTable.length; i++) {
          let {warehouse, _id} = this.useDisabledTable[i];
          if (warehouse && warehouse._id && this.productID === _id) {
            useList.push({
              warehouseID: warehouse._id,
              productID: _id,
            });
          }
        }

        console.log(useList);
        for (let i = 0; i < useList.length; i++) {
          let item = useList[i];

          for (let j = 0; j < this.options.length; j++) {
            let option = this.options[j];

            if (option.value._id === item.warehouseID) {
              option.disabled = true;
            }
          }
        }
        this.$forceUpdate();
        console.log(this.options, this.$forceUpdate);
      }
    },
    getWarehouseList(productID) {
      this.productID = productID;
      console.log("productID: " + productID);
      getWarehouseListByProductAndUserID({
        userID: getUserInfo().userID,
        productID,
      }).then(res => {
        let data = res.data.data;
        let arr = [];

        for (let i = 0; i < data.length; i++) {
          let inventory = data[i].inventory;
          if (isNotANumberOrEmpty(inventory)) {
            inventory = 0;
          }

          arr.push({
            label: `${data[i].warehouseName}`,
            inventory,
            value: data[i],
          });
        }

        if (this.value !== '') {
          this.innerValue = this.value;
        }
        this.options = arr;
        this.useDisabledTableMethod();
      });
    },
  }
}
</script>

<template>
  <el-select v-model="innerValue" style="flex: 1;" value-key="_id"
             filterable placeholder="">
    <el-option v-for="(item, index) in options"
               :key="Math.random()" :label="item.label" :disabled="item.disabled"
               :value="item.value">
      <span>{{item.label}}</span>(<span>{{item.inventory}}</span>)
    </el-option>
  </el-select>
</template>

<style scoped lang="scss">

</style>
